package com.gitee.wsl.ext.bitcode

import com.gitee.wsl.ext.base.Arrays
import com.gitee.wsl.ext.base.Arrays.copyOfRange


internal fun leftEncode(strLen: Long): ByteArray {
    var n: Byte = 1

    var v = strLen
    while ((8.let { v = v shr it.toInt(); v }) != 0L) {
        n++
    }

    val b = ByteArray(n + 1)

    b[0] = n

    for (i in 1..n) {
        b[i] = (strLen shr (8 * (n - i))).toByte()
    }

    return b
}

internal fun rightEncode(strLen: Long): ByteArray {
    var n: Byte = 1

    var v = strLen
    while ((8.let { v = v shr it.toInt(); v }) != 0L) {
        n++
    }

    val b = ByteArray(n + 1)

    b[n.toInt()] = n

    for (i in 0..<n) {
        b[i] = (strLen shr (8 * (n - i - 1))).toByte()
    }

    return b
}

fun encode(X: Byte): ByteArray {
    return Arrays.concatenate(leftEncode(8), byteArrayOf(X))!!
}

fun encode(`in`: ByteArray, inOff: Int, len: Int): ByteArray {
    if (`in`.size == len) {
        return Arrays.concatenate(leftEncode(len * 8L), `in`)!!
    }
    return Arrays.concatenate(leftEncode(len * 8L), copyOfRange(`in`, inOff, inOff + len))!!
}